package com.phone580.app.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;

import com.phone580.app.entity.AppInfoEntity;
import com.phone580.app.entity.AppUpgrageInfoEntity;
import com.phone580.app.entity.UpgradeEntity;
import com.phone580.app.untilty.CommonUtility;

public class AppUpgradeModel extends BaseModel {

	public final static String SUCCESS = "0";
	
	public AppUpgrageInfoEntity parseUpgradeResult(String xml) throws ParserConfigurationException, SAXException, IOException {
		AppUpgrageInfoEntity entity = new AppUpgrageInfoEntity();
		Element root = getDomRootElement(xml);
		String status = getContent(root, "ERROR_ID");
		String msg = getContent(root, "ERROR_MESS");
		entity.setStatus(status);
		entity.setMsg(msg);
		if (SUCCESS.equals(status)) {
			NodeList nodes = root.getElementsByTagName("APP_INFO");
			if (nodes.getLength() > 0) {
				List<UpgradeEntity> list = new ArrayList<UpgradeEntity>();
				for (int i = 0; i < nodes.getLength(); i++) {
					Element app = (Element)nodes.item(i);
					String id = getContent(app, "ID");
					String pkgName = getContent(app, "IDMARK");
					String version = getContent(app, "NEW_VERSION");
					String icon = getContent(app, "ICON_URL");
					String appURL = getContent(app, "APP_URL");
					String appName = getContent(app, "APP_NAME");
					UpgradeEntity upgrade = new UpgradeEntity();
					upgrade.setId(id);
					upgrade.setPkgName(pkgName);
					upgrade.setIconURL(icon);
					upgrade.setAppName(appName);
					upgrade.setAppURL(appURL);
					upgrade.setVersion(version);
					list.add(upgrade);
				}
				entity.setApps(list);
			}
		}
		return entity;
	}
	
	public String getRequestParams(Context context) {
		List<AppInfoEntity> list = CommonUtility.getMyAppList(context);
		StringBuilder sb = new StringBuilder();
		sb.append("<ROOT>");
		sb.append("<OPER_SYSTEM>51</OPER_SYSTEM>");
		sb.append("<APP_QRY_LIST>");
		for (AppInfoEntity entity : list) {
			sb.append("<APP_INFO>");
			sb.append("<IDMARK>" + entity.getPkgName() + "</IDMARK>");
			sb.append("<VERSION>" + entity.getVersion() + "</VERSION>");
			sb.append("</APP_INFO>");
		}
		sb.append("</APP_QRY_LIST>");
		sb.append("</ROOT>");
		return sb.toString();
	}
}
